package com.demo.task.ext

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.demo.task.service.BaseService
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

suspend inline fun <reified T> Context.bind() = suspendCancellableCoroutine {
    val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, iBinder: IBinder?) {
            if (iBinder is BaseService.BaseBinder) {
                val t = iBinder.getService() as T
                it.resume(t)
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            it.resume(null)
        }
    }

    val intent = Intent(this, T::class.java)
   bindService(intent, connection, Context.BIND_AUTO_CREATE)

    it.invokeOnCancellation {
        unbindService(connection)
    }
}